package mn.idax.exchange.otc.launch;

import mn.idax.exchange.otc.service.impl.RedisService;
import mn.idax.exchange.otc.util.LogUtils;
import mn.idax.exchange.otc.util.PairUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.swing.text.html.Option;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.*;

/**
 * @Auther: dison
 * @Date: 2018/7/31 13:33
 * @Description:
 */
@Component
public class CacheStartupRunner implements CommandLineRunner {

    @Autowired
    private RedisService redisService;

    @Override
    public void run(String... strings) throws Exception {
        String redisKeyPairs = "HashPairs";
        String redisKeyMarket = "HashMarket";
        long initialDelay11 = 1;
        long period12 = 60;
        ScheduledExecutorService pairAndSettingService =  new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-syncRedisPairsAndSettingCacheThread").daemon(true).build());
        ConcurrentHashMap pairConcurrentHashMap = new ConcurrentHashMap();
        ConcurrentHashMap pairMarketConcurrentHashMap = new ConcurrentHashMap();
        // 1.加载交易币种
        pairAndSettingService.scheduleAtFixedRate(() ->{
            try {
                Map map = redisService.getHashValue(redisKeyPairs);
                pairConcurrentHashMap.putAll(Optional.ofNullable(map).orElse(new ConcurrentHashMap()));
                PairUtils.putPairMap(pairConcurrentHashMap);
            } catch (Exception e) {
                LogUtils.error(this.getClass(), "初始化加载数据到内存中 syncRedisPairsAndSettingCacheThread exception ********************: ", e);
            }
        }, initialDelay11, period12, TimeUnit.SECONDS);

        // 2.加载市场成交价
        long initialDelay1 = 1;
        long period1 = 5;
        ScheduledExecutorService marketService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-syncRedisMarketCacheThread").daemon(true).build());
        marketService.scheduleAtFixedRate(() ->{
            try {
                Map mkMap = redisService.getHashValue(redisKeyMarket);
                pairMarketConcurrentHashMap.putAll(Optional.ofNullable(mkMap).orElse(new ConcurrentHashMap()));
                PairUtils.putPairMarketMap(pairMarketConcurrentHashMap);
            } catch (Exception e) {
                LogUtils.error(this.getClass(), "初始化加载数据到内存中 syncRedisMarketCacheThread exception ********************: ", e);
            }
        }, initialDelay1, period1, TimeUnit.SECONDS);


    }
}
